package db_tool;

import beans.Log;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import tree_util.Account;

import javax.servlet.http.HttpSession;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by xiang on 2017/7/9.
 *
 */
public class LogTool {

//    private static ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
//    private static com.common.SpringLogTool logTool = (com.common.SpringLogTool) context.getBean("logTool");
    private static String[] operation = {"增加", "删除", "更新"};
    public static final int INSERT_CODE = 0;
    public static final int DELETE_CODE = 1;
    public static final int UPDATE_CODE = 2;


    //把对应操作插入datalog数据库
    public static void insertIntoDataLog(int operationCode, String tableName, int rowAccount){
        HttpSession session = ServletActionContext.getRequest().getSession();
        Account account = (Account)session.getAttribute("account");     //取得用户ID


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        //取得当前时间
        String operationTime = simpleDateFormat.format(new Date());

        String logId = operationTime.replaceAll("-", "");//计算LogID
        logId = logId.replaceAll(" ", "");
        logId = logId.replaceAll(":", "");
        logId = "LOG"+logId;
        DBConnection dbConnection = DBConnection.getInstance();
        String insert = "INSERT INTO DataLog VALUES (?,?,?,?,?,?)";
        try {
            PreparedStatement preparedStatement = dbConnection.getPreparedStatement(insert);
            preparedStatement.setString(1, logId);
            preparedStatement.setString(2, account.getID());
            preparedStatement.setString(3, operation[operationCode]);
            preparedStatement.setString(4, operationTime);
            preparedStatement.setString(5, tableName);
            preparedStatement.setInt(6, rowAccount);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        logTool.insertIntoDataLog(new Log(logId, account.getID(), operation[operationCode], operationTime, tableName, rowAccount));
    }


}
